package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {


    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public String createCode(String email) {
        Random random = new Random();
        int randomNum = random.nextInt(1000000);
        String randomCode = String.format("%06d", randomNum);

        Calendar nowTime = Calendar.getInstance();
        Date date = nowTime.getTime();
        nowTime.add(Calendar.MINUTE, 10);
        Date expiretDate = nowTime.getTime();

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(randomCode);
        authCode.setCreatetime(date);
        authCode.setExpiretime(expiretDate);
        authCodeDao.save(authCode);
        return randomCode;
    }

    @Override
    public int validate(String email, String code) {
        AuthCode authCode=new AuthCode();
        authCode.setEmail(email);
        Sort sort = Sort.by(Sort.Order.desc("createtime"));
        List<AuthCode> authCodeList = authCodeDao.findAll(Example.of(authCode), sort);
        if (null == authCodeList || authCodeList.size() == 0) {
            System.out.println("邮箱错误");
            return 1;
        }
        authCode = authCodeList.get(0);
        if(!authCode.getCode().equals(code)){
            System.out.println("验证码错误");
            return 1;
        }
  /*      Date expiretime = authCode.getExpiretime();
        Date nowDate = new Date();
        if (nowDate.after(expiretime)) {
            System.out.println("验证码超时");
            return 2;
        }*/
        return 0;
    }
}
